package com.yubest.junit.asyntask;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;

/**
 * 分批，参照 guava Lists.partition 方法
 *
 * @Author: hweiyu
 * @Date: 2022/12/5 15:26
 */
public class PartitionList<T> extends AbstractList<List<T>> {

    private List<T> list;

    private Integer part;

    public PartitionList(List<T> list, Integer part) {
        this.list = null == list ? new ArrayList<>(0) : list;
        this.part = null == part ? this.list.size() : part;
    }

    @Override
    public List<T> get(int index) {
        int start = this.part * index;
        int end = Math.min(start + this.part, this.list.size());
        return this.list.subList(start, end);
    }

    @Override
    public int size() {
        if (this.list.isEmpty()) {
            return 0;
        }
        return (int) Math.ceil(this.list.size() * 1.0 / this.part);
    }
}
